package com.example.redisdemo.config;

import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;

import java.io.File;
import java.lang.reflect.Method;

public class IpUtil {
    public static   String getCityInfo(String ip){
        //获取文件路径
        String dbPath = IpUtil.class.getResource("/ip2region/ip2region.db").getPath();
        //创建文件
        File file = new File(dbPath);
        if (!file.exists()){
            System.out.println("文件不存在");
        }
        //查询的算法
        int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree

        try{
            //配置
            DbConfig config = new DbConfig();
            DbSearcher  dbSearcher = new DbSearcher(config,dbPath);
            Method  method =null;
            switch (algorithm){
                case  DbSearcher.BTREE_ALGORITHM:
                    method=dbSearcher.getClass().getMethod("btreeSearch", String.class);
                    break;
                case  DbSearcher.BINARY_ALGORITHM :
                    method=dbSearcher.getClass().getMethod("binarySearch", String.class);
                    break;
                case DbSearcher.MEMORY_ALGORITYM:
                    method=dbSearcher.getClass().getMethod("memorySearch", String.class);
                    break;
            }
            DataBlock dataBlock =null;
            //判断地址
            if (Util.isIpAddress(ip)==false){
                System.out.println("Error : Invalid ip address");
            }
            dataBlock = (DataBlock)method.invoke(dbSearcher,ip);
            return  dataBlock.getRegion();
        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;
    }
}
